﻿namespace IntellectShop.Web2.Hardware.Controllers
{
	using System;
	using System.Linq;
	using System.Web;
	using System.Web.Mvc;
	using IntellectShop.Web2.Hardware.ViewModels;

	[IntellectShop.Web2.Hardware.Code.NoCache]
	public class CartController : Controller
	{
		//
		// GET: /ShoppingCart/
		public ActionResult Index()
		{
			var cart = Common.Cart.CreateCart(this.HttpContext);
			// Set up our ViewModel
			var viewModel = new CartViewModel
			{
				CartItems = cart.GetCartItems(),
			};

			// Return the view
			return View(viewModel);
		}

		[HttpGet]
		public ActionResult AddToCartAjax()
		{
			throw new HttpException(404, "Page not found");
		}

		// AJAX: /ShoppingCart/AddToCartAjax/5
		[HttpPost]
		public ActionResult AddToCartAjax(int id)
		{
			var commodity = Common.Commodity.RetrieveByID(id);
			if (commodity == null)
				throw new HttpException(404, "Page not found");

			var cart = Common.Cart.CreateCart(this.HttpContext);
			cart.AddToCart(commodity);

			return Json(new { CartCount = cart.GetCount() });
		}

		//
		// AJAX: /ShoppingCart/RemoveFromCart/5
		[IntellectShop.Web2.Hardware.Code.HandleErrorWithELMAH]
		[HttpPost]
		public ActionResult RemoveFromCart(int id)
		{
			var cart = Common.Cart.CreateCart(this.HttpContext);
			var cartItem = Common.CartItem.RetrieveByID(id);
			if (cartItem == null)
				throw new HttpException(404, "Page not found");

			var commodity = cartItem.Commodity;
			if (commodity == null)
				throw new HttpException(404, "Page not found");

			int remainingItemsCount = cart.RemoveFromCart(id);
			// Display the confirmation message
			var results = new CartRemoveViewModel
			{
				Message = String.Format("'{0}' {1}", commodity.Name, Resources.Strings.HasBeenRemoved),
				CartTotal = cart.GetTotal().ToString(),
				CartCount = cart.GetCount(),
				DeleteId = id,
				RemainingItemsCount = remainingItemsCount
			};

			return Json(results);
		}

		//
		// GET: /ShoppingCart/CartSummary
		[IntellectShop.Web2.Hardware.Code.HandleErrorWithELMAH]
		[ChildActionOnly]
		public ActionResult CartSummary()
		{
			var cart = Common.Cart.CreateCart(this.HttpContext);
			ViewData["CartCount"] = cart.GetCount();
			return PartialView("CartSummary");
		}
	}
}
